package com.euond.permission.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.euond.common.core.dto.ResultDto;
import com.euond.common.core.dto.SerachMapDto;
import com.euond.common.core.exception.ServiceException;
import com.euond.common.core.service.impl.BaseServiceImpl;
import com.euond.permission.entities.Role;
import com.euond.permission.entities.UserRole;
import com.euond.permission.mapper.UserRoleMapper;
import com.euond.permission.service.UserPermissionService;
import com.euond.permission.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by user on 2017/7/20.
 */
@Service
public class UserRoleServiceImpl extends BaseServiceImpl<UserRoleMapper,UserRole> implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserPermissionService userPermissionService;

    /*
 * 重写基类insert方法
 */
    @Override
    @Transactional
    public boolean insert(UserRole userRole) {
        super.insert(userRole);
        try{
            //同时增加用户权限
            userPermissionService.addUserPermissionByUserRole(userRole);
            return true;
        }catch (ServiceException e) {
            return false;
        }
    }
    /*
 * 重写基类insertBatch方法
 */
    @Override
    @Transactional
    public boolean insertBatch(List<UserRole> entityList) {
        super.insertBatch(entityList);
        try{
            for(int i=0;i<entityList.size();i++){
                //同时增加用户权限
                userPermissionService.addUserPermissionByUserRole(entityList.get(i));
            }
            return true;
        }catch (ServiceException e) {
            return false;
        }
    }

    /*
    * 重写基类deleteBatchIds方法
    */
    @Override
    @Transactional
    public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
        try{
            //删除角色资源关系前先删除对应的用户权限
            List<UserRole> userRoleList=selectBatchIds(idList);
            for(int i=0;i<userRoleList.size();i++){
                //同时更新用户权限
                userPermissionService.updateUserPermissionByUser(userRoleList.get(i).getUserId());
            }
            return super.deleteBatchIds(idList);
        }catch (ServiceException e) {
            return false;
        }
    }

    /*
    * 重写基类delete方法
    */
    @Override
    @Transactional
    public boolean delete(Wrapper<UserRole> wrapper){
        try{
            List<UserRole> userRoleList=selectList(wrapper);
            for(int i=0;i<userRoleList.size();i++){
                //同时更新用户权限
                userPermissionService.updateUserPermissionByUser(userRoleList.get(i).getUserId());
            }
            return super.delete(wrapper);
        }catch (ServiceException e) {
            return false;
        }
    }

    /*
    * 重写基类deleteById方法
    */
    @Override
    @Transactional
    public boolean deleteById(Serializable id){
        try{
            //删除用户前先删除对应的用户权限
            UserRole userRole=selectById(id);
            //同时更新用户权限
            userPermissionService.updateUserPermissionByUser(userRole.getUserId());
            return super.deleteById(id);
        }catch (ServiceException e) {
            return false;
        }
    }

    /**
     * 查找用户角色关系（分页）  获取用户信息采用feign调用
     *
     * @param searchParams
     */
    public Page<UserRole>  findUserRoles(Map<String,Object> searchParams){
        UserRole userRole=new UserRole();
        SerachMapDto serachMapDto=new SerachMapDto(searchParams,userRole);
        Page<UserRole> page=new Page(serachMapDto.getPageCurrent(),serachMapDto.getPageSize());
        //假如存在需要扩展特殊的条件内容，则可以(UserRole)serachMapDto.getObject()重新赋值
        page.setRecords(userRoleMapper.findUserRoles(page,(UserRole)serachMapDto.getObject()));
        return page;

    }

    /**
     * 查找用户的角色（前端分页）
     * @param searchParams
     * @return
     */
    public ResultDto findUserAvailableRoles(Map<String,Object> searchParams)
    {
        UserRole userRole=new UserRole();
        SerachMapDto serachMapDto=new SerachMapDto(searchParams,userRole);
        Page<Role> page=new Page(serachMapDto.getPageCurrent(),serachMapDto.getPageSize());
        //假如存在需要扩展特殊的条件内容，则可以(UserRole)serachMapDto.getObject()重新赋值

        page.setRecords(userRoleMapper.findUserAvailableRoles(page,(UserRole)serachMapDto.getObject()));
        ResultDto resultDto=new ResultDto("0","seccess",page.getRecords(),page.getTotal());
        return resultDto;

    }

    /**
     * 查找用户的角色(不分页,用于shiro)
     * @param userId
     * @return
     */
    public List<Role> findUserAvailableRoles(Long userId){
        UserRole userRole=new UserRole();
        userRole.setUserId(userId);
        return userRoleMapper.findUserAvailableRoles(userRole);
    }

    /**
     * 按用户查找没有分配的角色
     * @param searchParams
     * @return
     */
    public ResultDto findUserNotAvailableRoles(Map<String,Object> searchParams){
        UserRole userRole=new UserRole();
        SerachMapDto serachMapDto=new SerachMapDto(searchParams,userRole);
        Page<Role> page=new Page(serachMapDto.getPageCurrent(),serachMapDto.getPageSize());
        //假如存在需要扩展特殊的条件内容，则可以(UserRole)serachMapDto.getObject()重新赋值

        page.setRecords(userRoleMapper.findUserNotAvailableRoles(page,(UserRole)serachMapDto.getObject()));
        ResultDto resultDto=new ResultDto("0","seccess",page.getRecords(),page.getTotal());
        return resultDto;
    }

    /**
     * 按角色Id删除角色用户
     * @param roleId
     * @return
     */
    public void deleteUserRoleByRoleId(Long roleId){
        EntityWrapper entityWrapper=new EntityWrapper();
        entityWrapper.eq("role_id",roleId);
        delete(entityWrapper);
    }

    /**
     * 按角色Id查找用户角色
     * @param roleId
     * @return
     */
    public List<UserRole> findUserRoleByRoleId(Long roleId){
        EntityWrapper entityWrapper=new EntityWrapper();
        entityWrapper.eq("role_id",roleId);
        return selectList(entityWrapper);
    }
}
